package com.bos.web.action;

import com.bos.domian.system.User;
import com.bos.service.UserService;
import com.bos.web.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * @author misterWei
 * @create 2018年12月23号:21点15分
 * @mailbox mynameisweiyan@gmail.com
 */
@ParentPackage("json-default")
@Actions
@Namespace("/")
@Controller
public class UserAction extends BaseAction<User> {
     @Autowired
     private UserService userService;

     private String[] roleIds;

    public void setRoleIds(String[] roleIds) {
        this.roleIds = roleIds;
    }

    @Action(value = "user_login",results = {
            @Result(name = "success",type = "redirect",location = "/index.html")
            ,@Result(name = "login",type = "redirect",location = "/login.html")})
    public String login(){

        try {
            //登陆成功
            Subject subject = SecurityUtils.getSubject();
            AuthenticationToken authenticationToken = new UsernamePasswordToken(model.getUsername(),model.getPassword());
            subject.login(authenticationToken);
            return SUCCESS;
        }catch (Exception e){
            //登陆失败
            e.printStackTrace();
            return LOGIN;
        }
    }
    @Action(value = "user_logout",results = {
            @Result(name = "success",type = "redirect",location = "/login.html")})
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout(); //退出登陆操作
        return SUCCESS;
    }

    @Action(value = "query_userList",results = {@Result(name = "success",type = "json")})
    public String queryUserList(){
       List<User> userList =  userService.findAll();
        ActionContext.getContext().getValueStack().push(userList);
        return SUCCESS;
    }
   @Action(value = "user_save",results = {@Result(name = "success",type = "redirect",location = "/pages/system/userlist.html")})
    public String userSave(){
        userService.save(model,roleIds);
        return SUCCESS;
   }

}
